angular.module('nonghua.controllers.sales', [])

    .controller('CompetitorsListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own competitors'),
            add:$rootScope.user_access('add competitors'),
            stats:$rootScope.user_access('view competitors stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:3
        };
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                year: $scope.dateOption.year,
            };
        };
        $scope.moduleTitle = "竞品价格";
        $scope.moduleName = "competitors";
        listCtrl($scope, $rootScope,"competitors_id","competitorsList", "competitors_list", $ionicSideMenuDelegate);
    })

    .controller('CapacityListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own capacity'),
            add:$rootScope.user_access('add capacity'),
            stats:$rootScope.user_access('view capacity stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:3
        };
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                year: $scope.dateOption.year,
            };
        };
        $scope.moduleTitle = "市场容量";
        $scope.moduleName = "capacity";
        listCtrl($scope, $rootScope,"capacity_id","capacityList", "capacity_list", $ionicSideMenuDelegate);
    })

    .controller('PlantStructureListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own plant_structure'),
            add:$rootScope.user_access('add plant_structure'),
            stats:$rootScope.user_access('view plant_structure stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:3
        };
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                year: $scope.dateOption.year,
            };
        };
        $scope.moduleTitle = "种植结构";
        $scope.moduleName = "plant_structure";
        listCtrl($scope, $rootScope,"plant_structure_id","plantStructureList", "plant_structure_list", $ionicSideMenuDelegate);
    })

    .controller('BrandSalesListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {

        $scope.access={
            list:$rootScope.user_access('view own brand_sales'),
            add:$rootScope.user_access('add brand_sales'),
            stats:$rootScope.user_access('view brand_sales stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:3
        };
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                year: $scope.dateOption.year,
            };
        };
        $scope.moduleTitle = "品牌销量";
        $scope.moduleName = "brand_sales";
        listCtrl($scope, $rootScope,"brand_sales_id","brandSalesList", "brand_sales_list", $ionicSideMenuDelegate);
    })

    .controller('SalesLogListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own sales_log'),
            add:$rootScope.user_access('add sales_log'),
            stats:$rootScope.user_access('view sales_log stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:3
        };
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                year: $scope.dateOption.year,
            };
        };
        $scope.moduleTitle = "工作日志";
        $scope.moduleName = "sales_log";
        listCtrl($scope, $rootScope,"sales_log_id","salesLogList", "sales_log_list", $ionicSideMenuDelegate);
    })

    .controller('CompetitorsDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory) {
        var listStateName = "competitors-list";
        var resourceName = "competitors_add";
        $scope.listName = "competitorsList";
        $scope.moduleTitle = "竞争品牌";
        $scope.moduleName = "competitors";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.access={
            list:$rootScope.user_access('view own competitors'),
            add:$rootScope.user_access('add competitors'),
            stats:$rootScope.user_access('view competitors stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            init_addr_id:!empty($scope.detail) && !empty($scope.detail.addr_id) ? $scope.detail.addr_id : "",
            level:3
        };
        $scope.dateOption={
            year:'',
            initYear:!empty($scope.detail) && !empty($scope.detail.date) ? get_year_month_day_from_date($scope.detail.date)['year'] : '',
            initMonth:!empty($scope.detail) && !empty($scope.detail.date) ? get_year_month_day_from_date($scope.detail.date)['month'] : '',
            month:'',
            day:'',
            level:2
        };
        $scope.fertilizerOption={
            value:'',
            params:
            {
                action: "get_fertilizer" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'肥料类别',
            initValue:!empty($scope.detail) && !empty($scope.detail.fertilizer_id) ? $scope.detail.fertilizer_id : ''
        };
        $scope.brandOption={
            value:'',
            params:
            {
                action: "get_brand" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'品牌类别',
            initValue:!empty($scope.detail) && !empty($scope.detail.brand_id) ? $scope.detail.brand_id : ''
        };
        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                competitors_id: !empty($scope.id) ? $scope.id : 0,
                addr_id: _get_address_id($scope.addressOption),
                year:  $scope.dateOption.year,
                fertilizer_id: $scope.fertilizerOption.value,
                brand_id: $scope.brandOption.value,
                date: $scope.dateOption.year+'-'+$scope.dateOption.month+'-01',
                n: $scope.detail.n,
                p:$scope.detail.p,
                k: $scope.detail.k,
                npk_total: $scope.detail.npk_total,
                sm: $scope.detail.sm,
                factory_price: $scope.detail.factory_price,
                arrival_price:$scope.detail.arrival_price,
                retail_price: $scope.detail.retail_price,
                rebate: $scope.detail.rebate,
                sales_policy: $scope.detail.sales_policy
            };
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        //if ($scope.id != "") {
                        //    $scope.detail.addr_id = params.addr_id;
                        //    $scope.detail.year = params.year;
                        //    $scope.detail.fertilizer_id = params.fertilizer_id;
                        //    $scope.detail.fertilizer_name =get_select_name($scope.fertilizerOption.optionSource,params.fertilizer_id);
                        //    $rootScope[$scope.listName][$scope.id] = $scope.detail;
                        //}
                        //$state.go(listStateName,{reload:true});
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })

    .controller('CapacityDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory) {

        var listStateName = "capacity-list";
        var resourceName = "capacity_add";
        $scope.listName = "capacityList";
        $scope.moduleTitle = "市场容量";
        $scope.moduleName = "capacity";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.access={
            list:$rootScope.user_access('view own capacity'),
            add:$rootScope.user_access('add capacity'),
            stats:$rootScope.user_access('view capacity stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            init_addr_id:!empty($scope.detail) && !empty($scope.detail.addr_id) ? $scope.detail.addr_id : "",
            level:3
        };
        $scope.dateOption={
            year:'',
            initYear:!empty($scope.detail) && !empty($scope.detail.year) ? $scope.detail.year : '',
            month:'',
            day:'',
            level:1
        };
        $scope.fertilizerOption={
            value:'',
            params:
                {
                    action: "get_fertilizer" //'plant','fertilizer','product','brand','sales_type','department_employee'
                },
            label:'肥料类别',
            initValue:!empty($scope.detail) && !empty($scope.detail.fertilizer_id) ? $scope.detail.fertilizer_id : ''
        };

        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                capacity_id: !empty($scope.id) ? $scope.id : 0,
                addr_id: _get_address_id($scope.addressOption),
                year:  $scope.dateOption.year,
                fertilizer_id: $scope.fertilizerOption.value,
                capacity: $scope.detail.capacity
            };
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        //if ($scope.id != "") {
                        //    $scope.detail.addr_id = params.addr_id;
                        //    $scope.detail.year = params.year;
                        //    $scope.detail.fertilizer_id = params.fertilizer_id;
                        //    $scope.detail.fertilizer_name = $scope.fertilizerOption.optionSource[params.fertilizer_id];
                        //    $rootScope[$scope.listName][$scope.id] = $scope.detail;
                        //}
                        //$state.go(listStateName);
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })

    .controller('BrandSalesDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory) {
        $scope.access={
            list:$rootScope.user_access('view own brand_sales'),
            add:$rootScope.user_access('add brand_sales'),
            stats:$rootScope.user_access('view brand_sales stats'),
        }
        var listStateName = "brand-sales-list";
        var resourceName = "brand_sales_add";
        $scope.listName = "brandSalesList";
        $scope.moduleTitle = "品牌销量";
        $scope.moduleName = "brand_sales";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }

        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            init_addr_id:!empty($scope.detail) && !empty($scope.detail.addr_id) ? $scope.detail.addr_id : "",
            level:3
        };

        $scope.dateOption={
            year:'',
            initYear:!empty($scope.detail) && !empty($scope.detail.year) ? $scope.detail.year : '',
            month:'',
            day:'',
            level:1
        };

        $scope.brandOption={
            value:'',
            params:
            {
                action: "get_brand" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'化肥品牌',
            initValue:!empty($scope.detail) && !empty($scope.detail.brand_id) ? $scope.detail.brand_id : ''
        };

        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                brand_sales_id: !empty($scope.id) ? $scope.id : 0,
                addr_id: _get_address_id($scope.addressOption),
                year:  $scope.dateOption.year,
                brand_id: $scope.brandOption.value,
                sales: $scope.detail.sales
            };
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        //if ($scope.id != "") {
                        //    $scope.detail.addr_id = params.addr_id;
                        //    $scope.detail.year = params.year;
                        //    $scope.detail.brand_id = params.brand_id;
                        //    $scope.detail.brand_name = $scope.brandOption.optionSource[params.brand_id];
                        //    $rootScope[$scope.listName][$scope.id] = $scope.detail;
                        //}
                        //$state.go(listStateName);
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })

    .controller('PlantStructureDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory) {
        var listStateName = "plant-structure-list";
        var resourceName = "plant_structure_add";
        $scope.listName = "plantStructureList";
        $scope.moduleTitle = "种植结构";
        $scope.moduleName = "plant_structure";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.access={
            list:$rootScope.user_access('view own plant_structure'),
            add:$rootScope.user_access('add plant_structure'),
            stats:$rootScope.user_access('view plant_structure stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            init_addr_id:!empty($scope.detail) && !empty($scope.detail.addr_id) ? $scope.detail.addr_id : "",
            level:5
        };
        $scope.dateOption={
            year:'',
            initYear:!empty($scope.detail) && !empty($scope.detail.year) ? $scope.detail.year : '',
            month:'',
            day:'',
            level:1
        };
        $scope.plantOption={
            value:'',
            params:
                {
                    action: "get_plant" //'plant','fertilizer','product','brand','sales_type','department_employee'
                },
            label:'作物名称',
            initValue:!empty($scope.detail) && !empty($scope.detail.plant_id) ? $scope.detail.plant_id : ''
        };

        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                plant_structure_id: !empty($scope.id) ? $scope.id : 0,
                addr_id: _get_address_id($scope.addressOption),
                year:  $scope.dateOption.year,
                plant_id: $scope.plantOption.value,
                quantity: $scope.detail.quantity
            };
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })
    
    .controller('SalesLogDetailCtrl', function($scope, $stateParams, $rootScope, $ionicLoading, $state,$ionicHistory) {
		var listStateName = "sales-log-list";
		var resourceName = "sales_log_add";
		$scope.listName = "salesLogList";
		$scope.moduleTitle = "工作日志";
		$scope.moduleName = "sales-log";
        $scope.detailEdit = {editDisabled:false};

		$scope.id = $stateParams.id != "0" ? $stateParams.id : '';
		if (!empty($scope.id)) {
			$scope.operation = "修改";
			$scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
		} else {
			$scope.operation = "添加";
			$scope.detail = {};
		}

		$scope.addressOption = {
			province: '',
			city: '',
			county: '',
			town: '',
			village: '',
			init_addr_id: !empty($scope.detail) && !empty($scope.detail.addr_id) ? $scope.detail.addr_id : "",
			level: 5
		};
		$scope.dateOption = {
			year: '',
			initYear: !empty($scope.detail) && !empty($scope.detail.year) ? $scope.detail.year : '',
			month: '',
			day: '',
			level: 3
		};

		$scope.submitForm = function(form) {
			var path_to_source = 'mobile_service_resources/' + resourceName;
			var params = {
				sales_log_id: !empty($scope.id) ? $scope.id : 0,
				addr_id: _get_address_id($scope.addressOption),
				phone: $scope.detail.phone,
				client: $scope.detail.client,
				contact: $scope.detail.contact,
				sales_log_date: $scope.detail.sales_log_date,
				salesman_id: $scope.detail.salesman_id,
				addr_details: $scope.detail.addr_details,
				work_title: $scope.detail.work_title,
				work_details: $scope.detail.work_details
			};
			$ionicLoading.show({
				content: '请稍后',
				animation: 'fade-in',
				showBackdrop: true,
				maxWidth: 200,
				showDelay: 0
			});
			_get_datasouce_result({
				path: path_to_source,
				param: params,
				resource: resourceName,
				success: function(data) {
					$ionicLoading.hide();
					if (data.option) {
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
						alert("操作成功！");
					} else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
					}
				},
				error: function(xhr, status, message) {
					$ionicLoading.hide();
					$state.go('error');
				}
			});
		}
	})
    
    .controller('RetailstoreListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own retailstore'),
            add:$rootScope.user_access('add retailstore'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:3
        };
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                year: $scope.dateOption.year,
            };
        };
        $scope.moduleTitle = "门店登记";
        $scope.moduleName = "retailstore";
        listCtrl($scope, $rootScope,"retailstore_id","retailstoreList", "retailstore_list", $ionicSideMenuDelegate);
    })

    .controller('RetailstoreDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory) {
        var listStateName = "retailstore-list";
        var resourceName = "retailstore_add";
        $scope.listName = "retailstoreList";
        $scope.moduleTitle = "门店登记";
        $scope.moduleName = "retailstore";
        $scope.detailEdit = {editDisabled:false};

        $scope.access={
            list:$rootScope.user_access('view own retailstore'),
            add:$rootScope.user_access('add retailstore'),
        }
        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            init_addr_id:!empty($scope.detail) && !empty($scope.detail.addr_id) ? $scope.detail.addr_id : "",
            level:5
        };

        $scope.sacfvarietyOption={
            value:'',
            params:
            {
                action: "get_sacfvariety" //'plant','fertilizer','product','brand','sales_type','department_employee',''sacfvariety'
            },
            label:'化肥品种',
            initValue:!empty($scope.detail) && !empty($scope.detail.sacfvariety_id) ? $scope.detail.sacfvariety_id : ''
        };
        $scope.plantOption={
            value:'',
            params:
                {
                    action: "get_plant" //'plant','fertilizer','product','brand','sales_type','department_employee'
                },
            label:'主要作物',
            initValue:!empty($scope.detail) && !empty($scope.detail.plant_id) ? $scope.detail.plant_id : ''
        };
        $scope.brandOption={
            value:'',
            params:
            {
                action: "get_brand" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'化肥品牌',
            initValue:!empty($scope.detail) && !empty($scope.detail.brands) ? $scope.detail.brands : ''
        };
        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                retailstore_id:!empty($scope.id) ? $scope.id : "",
                addr_id: _get_address_id($scope.addressOption),
                addr_details: $scope.detail.addr_details,
                name: $scope.detail.name,
                phone: $scope.detail.phone,
                width: $scope.detail.width,
                height: $scope.detail.height,
                farm_area: $scope.detail.farm_area,
                sales_1: $scope.detail.sales_1,
                sacfvariety_id:  $scope.sacfvarietyOption.value,//化肥品种
                plant_id: $scope.plantOption.value,//主要作物
                brand_id: $scope.brandOption.value//主要作物
            };
            console.log(params); 
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {

                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })
    .controller('BrandSalesStatsCtrl', function ($scope,$http,$ionicLoading,$ionicPopover,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own brand_sales'),
            add:$rootScope.user_access('add brand_sales'),
            stats:$rootScope.user_access('view brand_sales stats'),
        }
        $scope.moduleTitle = "品牌销量";
        $scope.moduleName = "brand_sales";
        $scope.statsMsg= "";
        /*******************************图表相关************************************/

        $scope.optionBrands = {
            tooltip : {
                trigger: 'item',
                formatter: "{c} ({d}%)"
            },
            calculable : false,
            series : [
                {
                    type:'pie',
                    radius : '55%',
                    center: ['50%', '60%'],
                    data:[]
                }
            ]
        };
        $scope.optionBrandSales = {
            show : true,

            tooltip : {
                trigger: 'axis'
            },
            legend: {
                data:['近年销量']
            },
            toolbox: {
                show : false
            },
            color : [ '#00a0a0' ],
            calculable : false,
            xAxis : [
                {
                    type : 'category',
                    data : []
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : [
                {
                    name: '近年销量',
                    type: 'bar',
                    data: []
                }
            ]
        };
        // popover
        _init_popover($scope,$ionicPopover);

        //date
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        //fertilizer

        $scope.getBrandSales = function($event){
            if(empty(geoName)){
                alert("地理位置 必选.");
                return;
            }
            if($scope.dateOption.year==""){
                alert("年份 必选.");
                return;
            }

            $scope.openPopover($event);
            $scope.pieChartBrands = echarts.init(document.getElementById('divBrands'));
            $scope.barChartBrandSales = echarts.init(document.getElementById('divBrandSales'));

            $scope.pieChartBrands.on(echarts.config.EVENT.CLICK, function (param) {
                var params = [];
                var geoLevel = getGeoLevel(geoName);
                params.push('parameters[national_id]=' + getNationalID(geoLevel, geoName));
                params.push('parameters[geo_level]=' + geoLevel);
                params.push('parameters[year]=' + $scope.dateOption.year);
                params.push('parameters[geo_name]=' + geoName);

                $http.get(Drupal.settings.site_path + '/api/brand_sales/' + param.name + '?' + params.join('&'), function (json) {
                    jQuery("#divBrandSales").css('display','');
                    $scope.optionBrandSales.xAxis[0].data = json.times;
                    $scope.optionBrandSales.series[0].data = json.values;
                    $scope.barChartBrandSales.setOption($scope.optionBrandSales, true);
                });
            });


            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });

            var params = [];
            var geoLevel = getGeoLevel(geoName);
            params.push('parameters[national_id]=' + getNationalID(geoLevel, geoName));
            params.push('parameters[geo_level]=' + geoLevel);
            params.push('parameters[year]=' + $scope.dateOption.year);
            params.push('parameters[geo_name]=' + geoName);
            $http.get( Drupal.settings.site_path+ '/api/brand_sales/?' + params.join('&'))
                .success(function (json) {
                    $ionicLoading.hide();

                    $scope.optionBrands.series[0].data = json.brands;
                    $scope.pieChartBrands.setOption($scope.optionBrands, true);
                })

        };
        initMap("#map_previous", "#map_next",$http);
    })
    .controller('CompetitorsStatsCtrl', function ($scope,$rootScope,$http,$ionicLoading,$ionicPopover) {
        $scope.access={
            list:$rootScope.user_access('view own competitors'),
            add:$rootScope.user_access('add competitors'),
            stats:$rootScope.user_access('view competitors stats'),
        }
        $scope.moduleTitle = "竞争品牌";
        $scope.moduleName = "competitors";
        $scope.statsMsg= "";
        /*******************************图表相关************************************/

        $scope.optionQoQ_competitors = {
            title : {
                text: '',
            },
            tooltip : {
                trigger: 'axis',
                formatter: function (params,ticket,callback) {
                    console.log(params)
                    var res = params[0].name;
                    for (var i = 0, l = params.length; i < l; i++) {
                        res += '<br/>' + params[i].seriesName + ' : ' + params[i].value;
                    }
                    setTimeout(function (){
                        // 仅为了模拟异步回调
                        callback(ticket, res);
                    }, 200)
                    return 'loading';
                }
            },
            legend: {
                data:[]
            },
            calculable : false,
            xAxis : [
                {
                    type : 'category',
                    boundaryGap : false,
                    categories : []
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : []
        };
        // popover
        _init_popover($scope,$ionicPopover);

        //date
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:2
        };
        //fertilizer
        $scope.fertilizerOption={
            value:'',
            params:
            {
                action: "get_fertilizer" //'plant','fertilizer','product','brand','sales_type','department_employee',''sacfvariety'
            },
            label:'化肥类别',
        };
        $scope.getCompetitors = function($event){
            if(empty(geoName)){
                alert("地理位置 必选.");
                return;
            }
            if($scope.dateOption.year==""){
                alert("年份 必选.");
                return;
            }
            if($scope.dateOption.month==""){
                alert("月份 必选.");
                return;
            }
            if($scope.fertilizerOption.value==""){
                alert("化肥类别 必选.");
                return;
            }

            $scope.openPopover($event);
            $scope.competitors = echarts.init(document.getElementById('divcompetitors'));
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            var params = [];
            params.push('parameters[year]=' + $scope.dateOption.year);

            var geoLevel = getGeoLevel(geoName);
            params.push('parameters[national_id]=' + getNationalID(geoLevel, geoName));
            params.push('parameters[geo_level]=' + geoLevel);
            params.push('parameters[year]=' + $scope.dateOption.year);
            params.push('parameters[month]=' + $scope.dateOption.month);
            params.push('parameters[geo_name]=' + (!geoName ? geoChain[geoChain.length-1] : geoName));
            params.push('parameters[fertilizer]=' + $scope.fertilizerOption.value)
            $http.get( Drupal.settings.site_path+ '/api/competitors?' + params.join('&'))
                .success(function (json) {
                    $ionicLoading.hide();
                    $scope.optionQoQ_competitors.legend.data = json.legend;
                    $scope.optionQoQ_competitors.xAxis[0].data = json.xAxis;
                    $scope.optionQoQ_competitors.series = json.yAxis;
                    $scope.competitors.setOption( $scope.optionQoQ_competitors, true);
                })

        };
        initMap("#map_previous", "#map_next",$http);
    })
    .controller('PlantStructureStatsCtrl', function ($scope,$http,$ionicLoading,$ionicPopover,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own plant_structure'),
            add:$rootScope.user_access('add plant_structure'),
            stats:$rootScope.user_access('view plant_structure stats'),
        }
        $scope.moduleTitle = "种植结构";
        $scope.moduleName = "plant_structure";
        $scope.statsMsg= "";
        /*******************************图表相关************************************/
        /* 经济作物饼状图选项、参数 */
        $scope.optionEconomics = {
            title : {
                text: '经济作物',
                x:'center'
            },
            tooltip : {
                trigger: 'item',
                formatter: "{b} : {c} ({d}%)"
            },
            animantion: false,
            calculable : false,
            series : [
                {
                    type:'pie',
                    radius : '55%',
                    center: ['50%', '60%'],
                    data:[]
                }
            ]
        };
        $scope.optionGrains = {
            title : {
                text: '粮食作物',
                x:'center'
            },
            tooltip : {
                trigger: 'item',
                formatter: "{b} : {c} ({d}%)"
            },
            animantion: false,
            calculable : false,
            series : [
                {
                    type:'pie',
                    radius : '55%',
                    center: ['50%', '60%'],
                    data:[]
                }
            ]
        };
        $scope.optionVeges = {
            title : {
                text: '蔬菜水果',
                x:'center'
            },
            tooltip : {
                trigger: 'item',
                formatter: "{b} : {c} ({d}%)"
            },
            animantion: false,
            calculable : false,
            series : [
                {
                    type:'pie',
                    radius : '55%',
                    center: ['50%', '60%'],
                    data:[]
                }
            ]
        };
        // popover
        _init_popover($scope,$ionicPopover);
        /* 化肥饼状图选项、参数 */
        //date
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        $scope.getPlantStructure = function($event){
            if(empty(geoName)){
                alert("地理位置 必选.");
                return;
            }
            if($scope.dateOption.year==""){
                alert("年份 必选.");
                return;
            }

            $scope.openPopover($event);
            $scope.pieChartEconomics = echarts.init(document.getElementById('divEconomics'));
            $scope.pieChartGrains = echarts.init(document.getElementById('divGrains'));
            $scope.pieChartVeges = echarts.init(document.getElementById('divVeges'));
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            var params = [];
            var geoLevel = getGeoLevel(geoName);
            params.push('parameters[national_id]=' + getNationalID(geoLevel, geoName));
            params.push('parameters[geo_level]=' + geoLevel);
            params.push('parameters[year]=' + $scope.dateOption.year);
            params.push('parameters[geo_name]=' + (!geoName ? geoChain[geoChain.length-1] : geoName));
            $http.get( Drupal.settings.site_path+'/api/plant_structure?' + params.join('&'))
                .success(function (json) {

                $ionicLoading.hide();
                // 更新经济作物饼状图
                $scope.optionEconomics.series[0].data = json.economics;
                $scope.pieChartEconomics.setOption($scope.optionEconomics, true);

                // 更新粮食作物饼状图
                $scope.optionGrains.series[0].data = json.grains;
                $scope.pieChartGrains.setOption($scope.optionGrains, true);

                // 更新蔬菜水果饼状图
                $scope.optionVeges.series[0].data = json.veges;
                $scope.pieChartVeges.setOption($scope.optionVeges, true);
            })

        };
        initMap("#map_previous", "#map_next",$http);
    })
    .controller('CapacityStatsCtrl', function ($scope,$rootScope,$http,$ionicLoading,$ionicPopover) {
        $scope.access={
            list:$rootScope.user_access('view own capacity'),
            add:$rootScope.user_access('add capacity'),
            stats:$rootScope.user_access('view capacity stats'),
        }
        // popover
        $scope.statsMsg= "";
        _init_popover($scope,$ionicPopover);
        /* 化肥饼状图选项、参数 */
        $scope.optioncapacity = {
            title : {
                text: '化肥市场容量',
                x:'center'
            },
            tooltip : {
                trigger: 'item',
                formatter: "{b} : {c} ({d}%)"
            },
            animantion: false,
            calculable : false,
            series : [
                {
                    type:'pie',
                    radius : '55%',
                    center: ['50%', '60%'],
                    data:[]
                }
            ]
        };
        //date
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        $scope.getCapacity = function($event){
            if(empty(geoName)){
                alert("地理位置 必选.");
                return;
            }
            if($scope.dateOption.year==""){
                alert("年份 必选.");
                return;
            }

            $scope.openPopover($event);
            $scope.pieChartCapacity = echarts.init(document.getElementById('divcapacity'));
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            var params = [];
            var geoLevel = getGeoLevel(geoName);
            params.push('parameters[national_id]=' + getNationalID(geoLevel, geoName));
            params.push('parameters[geo_level]=' + geoLevel);
            params.push('parameters[year]=' + $scope.dateOption.year);
            params.push('parameters[geo_name]=' + (!geoName ? geoChain[geoChain.length-1] : geoName));

            $http.get(Drupal.settings.site_path + '/api/capacity?' + params.join('&'))
                .success(function (json) {
                    if(json.fertilizer.length<1){
                        $scope.statsMsg = "没有数据!";
                    }
                    $ionicLoading.hide();
                    // 更新化肥饼状图
                    $scope.optioncapacity.series[0].data = json.fertilizer;
                    $scope.pieChartCapacity.setOption($scope.optioncapacity, true);
                });
        };
        initMap("#map_previous", "#map_next",$http);
    });


